package org.example.memora.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.memora.common.result.Result;
import org.example.memora.entity.ChatMessage;
import org.example.memora.service.ChatMessageProducer;
import org.example.memora.service.ChatMessageService;
import org.example.memora.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.example.memora.service.NotificationService;

import java.time.Duration;
import java.time.Instant;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/chat")
@Tag(name = "社群聊天", description = "WebSocket 聊天处理、聊天记录、在线用户统计等接口")
public class CommunityChatController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CommunityService communityService;

    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private ChatMessageProducer chatMessageProducer;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;


//    @MessageMapping("/chat/{communityId}")
//    @SendTo("/topic/chat/{communityId}")
//    public ChatMessage handleChat(@DestinationVariable Long communityId, @Payload ChatMessage message) {
//        //log.info("收到原始消息: {}", message);
//
//        if (!communityService.isMember(communityId, message.getSenderId())) {
//            throw new RuntimeException("非社群成员，不允许发送消息");
//        }
//
//        message.setCommunityId(communityId);
//        message.setCreatedAt(Instant.now());
//        chatMessageService.save(message);
//        return message;
//    }
//@MessageMapping("/chat/{communityId}")
//public void handleChat(@DestinationVariable Long communityId, @Payload ChatMessage message) {
//    // 1. 校验发送者是否是社群成员
//    if (!communityService.isMember(communityId, message.getSenderId())) {
//        throw new RuntimeException("非社群成员，不允许发送消息");
//    }
//
//    // 2. 封装消息内容
//    message.setCommunityId(communityId);
//    message.setCreatedAt(Instant.now());
//
//    // 3. 发送到 RabbitMQ 队列
//    chatMessageProducer.send(message);
//}
@MessageMapping("/chat/{communityId}")
public void handleChat(@DestinationVariable Long communityId, @Payload ChatMessage message) {
    Long senderId = message.getSenderId();
    String redisKey = "community:members:" + communityId;
    if (message.getMessageType() == null) {
        message.setMessageType("text");
    }


    // 尝试从 Redis 缓存查成员
    Boolean isMember = stringRedisTemplate.opsForSet().isMember(redisKey, String.valueOf(senderId));

    if (Boolean.FALSE.equals(isMember)) {
        // Redis 中没有记录，查询数据库
        boolean dbResult = communityService.isMember(communityId, senderId);
        if (!dbResult) {
            throw new RuntimeException("非社群成员，不允许发送消息");
        }

        // 写入缓存，防止下次重复查库
        stringRedisTemplate.opsForSet().add(redisKey, String.valueOf(senderId));
        // 设置过期时间（可选）
        stringRedisTemplate.expire(redisKey, Duration.ofMinutes(60));
    }

    // 2. 封装消息内容
    message.setCommunityId(communityId);
    message.setCreatedAt(Instant.now());
    log.info("发送原始消息: {}", message);

    // 3. 发送到 RabbitMQ 队列
    chatMessageProducer.send(message);
    messagingTemplate.convertAndSend("/topic/chat/" + message.getCommunityId(), message);
    //chatMessageService.save(message);
}



    @Operation(summary = "获取历史聊天记录", description = "分页查询指定社群的历史聊天消息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/history")
    public Result<List<ChatMessage>> getHistory(
            @Parameter(description = "社群ID", required = true) @RequestParam Long communityId,
            @Parameter(description = "页码，默认为1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小，默认为20") @RequestParam(defaultValue = "20") Integer size) {
        log.info("获取社群[{}]的聊天历史，page={}, size={}", communityId, page, size);
        return Result.success(chatMessageService.getHistory(communityId, page, size));
    }

    @Operation(summary = "获取在线用户数", description = "获取当前社群聊天室在线用户的数量")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/online/count")
    public Result<Long> getOnlineCount(
            @Parameter(description = "社群ID", required = true) @RequestParam Long communityId) {
        log.info("获取社群[{}]在线用户数", communityId);
        String key = "chat:online:" + communityId;
        Long count = stringRedisTemplate.opsForSet().size(key);
        return Result.success(count);
    }
}
